package com.mrx.compose.test.ui.pixiv

import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.awt.ComposeWindow
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.res.loadImageBitmap
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import com.mrx.compose.test.config.WindowConfig
import com.mrx.compose.test.ui.BaseWindow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import java.awt.FileDialog
import java.io.ByteArrayInputStream
import java.io.File
import java.io.InputStream
import kotlin.coroutines.CoroutineContext

object PixivWindow : BaseWindow(), CoroutineScope {

    override val title = "Pixiv 图片预览"
    override val size = DpSize(400.dp, 400.dp)
    override val scrollbar: Boolean = false
    override val coroutineContext: CoroutineContext = Dispatchers.IO

    private val client = OkHttpClient.Builder()
        .addNetworkInterceptor {
            println("正在请求: ${it.request().url}")
            it.proceed(it.request())
        }.build()

    private fun picURL(pid: Int) = "https://pixiv.re/$pid.png"

    @Composable
    override fun app(window: ComposeWindow) {
        Column {
            val painter = remember { mutableStateOf(WindowConfig.image) }
            var clickable by remember { mutableStateOf(false) }
            var imageBytes by remember { mutableStateOf(byteArrayOf()) }
            Row(
                modifier = Modifier.padding(top = 10.dp, bottom = 10.dp).fillMaxWidth(),
                horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically
            ) {
                var value by remember { mutableStateOf(TextFieldValue("82775556")) }
                var isError by remember { mutableStateOf(false) }
                OutlinedTextField(
                    value,
                    label = { Text("输入 pixiv Id") },
                    placeholder = { Text("输入 pixiv Id") },
                    isError = isError,
                    onValueChange = {
                        isError = if (it.text.chars().allMatch(Character::isDigit)) {
                            value = it
                            false
                        } else {
                            true
                        }
                    })
                Button(
                    modifier = Modifier.padding(start = 10.dp),
                    onClick = {
                        launch {
                            imageBytes = loadImage(value.text.toInt()).readAllBytes()
                            painter.value = BitmapPainter(loadImageBitmap(ByteArrayInputStream(imageBytes)))
                            clickable = true
                        }
                    },
                ) { Text("获取图片") }
            }
            Image(painter.value, "", Modifier.clickable(enabled = clickable) {
                val (directory, file) = FileDialog(window, "请选择保存路径", FileDialog.SAVE)
                    .apply { isVisible = true }
                if (directory != null && file != null) {
                    val saveFile = "$directory$file"
                    File(saveFile).writeBytes(imageBytes)
                }
            })
        }
    }

    private fun loadImage(pid: Int): InputStream {
        val call = client.newCall(Request.Builder().url(picURL(pid)).build())
        return call.execute().body!!.byteStream()
    }

    private operator fun FileDialog.component1() = directory
    private operator fun FileDialog.component2() = file
}
